package com.thinkSoft.Location.Helpers;

import org.json.JSONException;
import org.json.JSONObject;

import com.thinkSoft.Location.Lib.DataFunc;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;

public class MotdCheck extends AsyncTask < String , Context , Void > {
        private Context targetCtx ;
        private String message = "";
        private String title = "";
        private static String KEY_SUCCESS = "success";
        private static String KEY_MESSAGE = "message";
        private static String KEY_TITLE = "title";
        private static String KEY_UID = "uid";
        public MotdCheck ( Context context ) {
            this.targetCtx = context ;
        }

        @ Override
        protected Void doInBackground ( String ... params ) {
        	 DataFunc userFunction = new DataFunc();
             JSONObject json = userFunction.getMOTD();
             userFunction.sendDeviceInfo(targetCtx);

             try {
                 if (json.getString(KEY_SUCCESS) != null) {
                     String res = json.getString(KEY_SUCCESS);                     
                     if(Integer.parseInt(res) == 1){
                    	 SharedPreferences reader = targetCtx.getSharedPreferences("LocationApp",
                                 Activity.MODE_PRIVATE);
                    	 if (!reader.getString("motduid", "").equals(json.getString(KEY_UID))){
	                     	message = json.getString(KEY_MESSAGE);
	                     	title = json.getString(KEY_TITLE);
	                     	SharedPreferences settings = targetCtx.getSharedPreferences("LocationApp", 0);
	                        SharedPreferences.Editor editor = settings.edit();
	                        editor.putString("motduid",
	                                json.getString(KEY_UID));
	                        editor.commit();
                    	 }
                     }else{
                         message = "";
                     }
                 }
             } catch (JSONException e) {
                 e.printStackTrace();
             }
            return null;
        }

        @ Override
        protected void onPostExecute ( Void result ) {
        	if (message != ""){
        		new AlertDialog.Builder(targetCtx).setTitle(title).setMessage(message).setNeutralButton("Close", null).show();
        	}    
        }
    }